#include "chartwidget.h"
#include "ui_chartwidget.h"
#include <QDebug>
#include <QPainter>//画图头文件
#include <QDesktopWidget>
#include <QScreen>
#include <QMessageBox>
#include <QMetaEnum>

ChartWidget::ChartWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ChartWidget)
{
    ui->setupUi(this);

    startInit();

    ui->statusBar->setText(tr("串口关闭"));
    setGeometry(400, 250, 542, 390);
    dataTimer = new QTimer(this);
    connect(dataTimer, SIGNAL(timeout()), this, SLOT(realtimeDataSlot()));
}

//初始化
void ChartWidget::startInit()
{
  ui->StartChartbtn->setEnabled(true);
  ui->StopChartbtn->setEnabled(false);

    //初始化读取定时器计时间隔
    timerdly = TIMER_INTERVAL;
    //设置读取计时器
    readTimerA = new QTimer(this);
    connect(readTimerA, SIGNAL(timeout()), this, SLOT(readMyComA()));
}


void ChartWidget::setComboBoxEnabled(bool status)
{
    ui->portNameComboBox->setEnabled(status);
    ui->baudRateComboBox->setEnabled(status);
    ui->dataBitsComboBox->setEnabled(status);
    ui->parityComboBox->setEnabled(status);
    ui->stopBitsComboBox->setEnabled(status);
}

ChartWidget::~ChartWidget()
{
    delete ui;
}

void ChartWidget::on_StartChartbtn_clicked()
{
    QString portName = "/dev/" + ui->portNameComboBox->currentText();   //获取串口名
    myComA = new Posix_QextSerialPort(portName, QextSerialBase::Polling);
    //这里QextSerialBase::QueryMode应该使用QextSerialBase::Polling

    if(myComA->open(QIODevice::ReadOnly)){
           ui->statusBar->setText(tr("串口打开成功"));
    }else{
           ui->statusBar->setText(tr("串口打开失败"));
        return;
    }
    //设置波特率
    myComA->setBaudRate((BaudRateType)ui->baudRateComboBox->currentIndex());

    //设置数据位
    myComA->setDataBits((DataBitsType)ui->dataBitsComboBox->currentIndex());

    //设置校验
    myComA->setParity((ParityType)ui->parityComboBox->currentIndex());

    //设置停止位
    myComA->setStopBits((StopBitsType)ui->stopBitsComboBox->currentIndex());
    //设置数据流控制
    myComA->setFlowControl(FLOW_OFF);
    //设置延时
    myComA->setTimeout(TIME_OUT);

    setComboBoxEnabled(false);

    readTimerA->start(TIMER_INTERVAL);
    ui->StartChartbtn->setEnabled(false);
    ui->StopChartbtn->setEnabled(true);
}

//读取串口A并显示出来
void ChartWidget::readMyComA()
{

    QByteArray temp = myComA->readAll();
    QString  str=QString(temp);
    bool ok;
       //取数据，发信号，各FORM接收处理
    if(!temp.isEmpty())
    {

        if(str.indexOf("0102")>=0)
        {
            QString  humidity=str.mid((str.indexOf("0102")+4),2);
         ui->lineEdithum->setText(humidity);
             humdata=humidity.toInt(&ok);
               qDebug()<<humdata;

        }

        if(str.indexOf("0101")>=0)
         {

           QString  temprature=str.mid((str.indexOf("0101")+4),2);

            ui->lineEdittemp->setText(temprature);

            tempdata=temprature.toInt(&ok);



             setupRealtimeDataDemo(ui->customPlot);
         //    ui->customPlot->replot();

         }

    }
}

void ChartWidget::setupRealtimeDataDemo(QCustomPlot *customPlot)
{
#if QT_VERSION < QT_VERSION_CHECK(4, 7, 0)
  QMessageBox::critical(this, "", "You're using Qt < 4.7, the realtime data demo needs functions that are available with Qt 4.7 to work properly");
#endif
 // demoName = "Real Time Data Demo";

  customPlot->addGraph(); // blue line
  customPlot->graph(0)->setPen(QPen(Qt::blue));
  customPlot->graph(0)->setBrush(QBrush(QColor(240, 255, 200)));
  customPlot->graph(0)->setAntialiasedFill(false);
  customPlot->addGraph(); // red line
  customPlot->graph(1)->setPen(QPen(Qt::red));
  customPlot->graph(0)->setChannelFillGraph(customPlot->graph(1));

  customPlot->addGraph(); // blue dot
  customPlot->graph(2)->setPen(QPen(Qt::blue));
  customPlot->graph(2)->setLineStyle(QCPGraph::lsNone);
  customPlot->graph(2)->setScatterStyle(QCPScatterStyle::ssDisc);
  customPlot->addGraph(); // red dot
  customPlot->graph(3)->setPen(QPen(Qt::red));
  customPlot->graph(3)->setLineStyle(QCPGraph::lsNone);
  customPlot->graph(3)->setScatterStyle(QCPScatterStyle::ssDisc);

  customPlot->xAxis->setTickLabelType(QCPAxis::ltDateTime);
  customPlot->xAxis->setDateTimeFormat("hh:mm:ss");
  customPlot->xAxis->setAutoTickStep(false);
  customPlot->xAxis->setTickStep(2);
  customPlot->axisRect()->setupFullAxesBox();

  // make left and bottom axes transfer their ranges to right and top axes:
  connect(customPlot->xAxis, SIGNAL(rangeChanged(QCPRange)), customPlot->xAxis2, SLOT(setRange(QCPRange)));
  connect(customPlot->yAxis, SIGNAL(rangeChanged(QCPRange)), customPlot->yAxis2, SLOT(setRange(QCPRange)));

  // setup a timer that repeatedly calls MainWindow::realtimeDataSlot:

  dataTimer->start(10); // Interval 0 means to refresh as fast as possible
}

void ChartWidget::realtimeDataSlot()
{
  // calculate two new data points:
#if QT_VERSION < QT_VERSION_CHECK(4, 7, 0)
  double key = 0;
#else
  double key = QDateTime::currentDateTime().toMSecsSinceEpoch()/1000.0;
#endif
  static double lastPointKey = 0;
  if (key-lastPointKey > 0.01) // at most add point every 10 ms
  {
  //  double value0 = qSin(key); //sin(key*1.6+cos(key*1.7)*2)*10 + sin(key*1.2+0.56)*20 + 26;
  //  double value1 = qCos(key); //sin(key*1.3+cos(key*1.2)*1.2)*7 + sin(key*0.9+0.26)*24 + 26;
    // add data to lines:
    ui->customPlot->graph(0)->addData(key, tempdata);
    ui->customPlot->graph(1)->addData(key, humdata);
    // set data of dots:
    ui->customPlot->graph(2)->clearData();
    ui->customPlot->graph(2)->addData(key, tempdata);
    ui->customPlot->graph(3)->clearData();
    ui->customPlot->graph(3)->addData(key, humdata);
    // remove data of lines that's outside visible range:
    ui->customPlot->graph(0)->removeDataBefore(key-8);
    ui->customPlot->graph(1)->removeDataBefore(key-8);
    // rescale value (vertical) axis to fit the current data:
    ui->customPlot->graph(0)->rescaleValueAxis();
    ui->customPlot->graph(1)->rescaleValueAxis(true);
    lastPointKey = key;
  }
  // make key axis range scroll with the data (at a constant range size of 8):
  ui->customPlot->xAxis->setRange(key+0.5, 10, Qt::AlignRight);
 // ui->customPlot->xAxis->setRange(10, 8, Qt::AlignRight);
  ui->customPlot->replot();
/*
  // calculate frames per second:
  static double lastFpsKey;
  static int frameCount;
  ++frameCount;
  if (key-lastFpsKey > 2) // average fps over 2 seconds
  {
    ui->statusBar->showMessage(
          QString("%1 FPS, Total Data points: %2")
          .arg(frameCount/(key-lastFpsKey), 0, 'f', 0)
          .arg(ui->customPlot->graph(0)->data()->count()+ui->customPlot->graph(1)->data()->count())
          , 0);
    lastFpsKey = key;
    frameCount = 0;
  }
  */
}


void ChartWidget::on_StopChartbtn_clicked()
{
    myComA->close();
    delete myComA;
    dataTimer->stop();
    readTimerA->stop();
    ui->statusBar->setText(tr("串口关闭"));
    setComboBoxEnabled(true);
    ui->StartChartbtn->setEnabled(true);
    ui->StopChartbtn->setEnabled(false);
}
